﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PerfumeShopManagement.Model;
using PerfumeShopManagement.Utility;

namespace PerfumeShopManagement.DAL
{
    public class DalCategory : DalAbstractBase<Category, int>
    {
        public override Category GetObjectById(int id)
        {
            throw new NotImplementedException();
        }

        public override List<Category> GetAllObjects()
        {
            var result = (from c in _context.Categories
                          select c);
            if (result != null)
                return result.ToList<Category>();

            return new List<Category>();
        }

        public override List<Category> GetObjectsByCriteria(Category obj)
        {
            Category category = obj;

            var categoriesQuery = (from c in _context.Categories
                              select c);

            if (category.CategoryId != 0)
                categoriesQuery = categoriesQuery.Where(c => c.CategoryId.Equals(category.CategoryId));

            if (!StringUtil.isEmptyOrBlank(category.CategoryName))
                categoriesQuery = categoriesQuery.Where(c => c.CategoryName.Contains(category.CategoryName));

            if (categoriesQuery != null)
                return categoriesQuery.ToList<Category>();

            return new List<Category>();
        }

        public override bool Insert(Category obj)
        {
            Category category = obj;

            _context.Categories.AddObject(category);
            _context.SaveChanges();

            return true;
        }

        public override bool Update(Category obj)
        {
            Category category = obj;

            Category categoryRow = _context.Categories.Single(
                c => c.CategoryId == category.CategoryId);
            categoryRow.CategoryName = category.CategoryName;
            _context.SaveChanges();

            return true;
        }

        public override bool DeleteById(int id)
        {
            bool deleted = false;
            int categoryId = id;
            var result = (from c in _context.Categories
                          where c.CategoryId.Equals(categoryId)
                          select c).FirstOrDefault();
            if (result != null)
            {
                _context.Categories.DeleteObject((Category)result);
                _context.SaveChanges();
                deleted = true;
            }

            return deleted;
        }
    }
}
